package mvc.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ConfigParse {
	static Map<String, XmlBean> parse(String xmlpath) {
		Map<String, XmlBean> configmap = new HashMap<String, XmlBean>();
		SAXBuilder saxb = new SAXBuilder();
		try {
			Document doc = saxb.build(new File(xmlpath));
			Element root = doc.getRootElement();
			Element formbeans = root.getChild("form-beans");
			List<Element> forms = formbeans.getChildren();
			Map<String, String> formmap = new HashMap<String, String>();
			for (Element form : forms) {
				formmap.put(form.getAttributeValue("name"),
						form.getAttributeValue("type"));
			}

			Element actionmappings = root.getChild("action-mappings");
			List<Element> actions = actionmappings.getChildren();
			for (Element action : actions) {
				XmlBean xmlb = new XmlBean();
				String actionname = action.getAttributeValue("name");
				xmlb.setActionname(actionname);
				String actiontype = action.getAttributeValue("type");
				xmlb.setActiontype(actiontype);
				String path = action.getAttributeValue("path");
				xmlb.setPath(path);
				xmlb.setFormtype(formmap.get(actionname));

				List<Element> forwards = action.getChildren();
				Map<String, String> mappingforward = new HashMap<String, String>();
				for (Element forward : forwards) {
					mappingforward.put(forward.getAttributeValue("name"),
							forward.getAttributeValue("value"));
				}
				xmlb.setForward(mappingforward);
				configmap.put(path, xmlb);
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return configmap;
	}
}
